import { useEffect, useState, type FormEvent, type ReactNode } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { EnvelopeIcon, LockClosedIcon, UserIcon } from '@heroicons/react/24/outline'
import { Link, useLocation, useNavigate } from 'react-router-dom'

import { AuthAPI, type LoginPayload } from '../app/api'
import { useAuthStore } from '../app/store/authStore'

type AuthMode = 'login' | 'register'

type FormFieldProps = {
  label: string
  name: string
  placeholder: string
  type?: string
  icon?: ReactNode
}

const AuthPage = () => {
  if (typeof document !== 'undefined') document.title = '登录 / 注册 · Love Notes'
  const [mode, setMode] = useState<AuthMode>('login')
  const [loginIdentifier, setLoginIdentifier] = useState<'email' | 'username'>('email')
  const [error, setError] = useState<string | null>(null)
  const [info, setInfo] = useState<string | null>(null)
  const [verificationPending, setVerificationPending] = useState(false)
  const [rememberMe, setRememberMe] = useState(true)
  const [pendingEmail, setPendingEmail] = useState<string | null>(null)
  const [pendingPassword, setPendingPassword] = useState<string | null>(null)
  const [pendingUsername, setPendingUsername] = useState<string | null>(null)
  const [verificationCode, setVerificationCode] = useState('')
  const navigate = useNavigate()
  const location = useLocation()
  const queryClient = useQueryClient()

  const accessToken = useAuthStore((state) => state.accessToken)
  const setTokens = useAuthStore((state) => state.setTokens)
  const setUser = useAuthStore((state) => state.setUser)
  const setRemember = useAuthStore((state) => state.setRemember)

  const loginMutation = useMutation({ mutationFn: AuthAPI.login })
  const registerMutation = useMutation({ mutationFn: AuthAPI.register })
  const verifyEmailMutation = useMutation({ mutationFn: AuthAPI.verifyEmail })
  const resendVerificationMutation = useMutation({ mutationFn: AuthAPI.resendVerification })

  useEffect(() => {
    if (accessToken) {
      navigate('/dashboard', { replace: true })
    }
  }, [accessToken, navigate])

  const parseError = (err: unknown) => {
    if (err instanceof Error) {
      try {
        const parsed = JSON.parse(err.message)
        if (parsed && typeof parsed === 'object' && 'detail' in parsed && typeof parsed.detail === 'string') {
          return parsed.detail
        }
      } catch {
        // fall through to original message
      }
      return err.message
    }
    return '操作失败，请稍后重试'
  }

  const resetVerificationState = () => {
    setVerificationPending(false)
    setPendingEmail(null)
    setPendingPassword(null)
    setPendingUsername(null)
    setVerificationCode('')
  }

  const finalizeLogin = async (payload: LoginPayload) => {
    const tokens = await loginMutation.mutateAsync(payload)
    // 先设置记住我选项以决定写入的存储介质
    setRemember(rememberMe)
    setTokens(tokens)

    const profile = await AuthAPI.getProfile()
    setUser(profile)
    await queryClient.invalidateQueries({ queryKey: ['me'] })

    const state = location.state as { from?: { pathname: string } } | undefined
    const redirectPath = state?.from?.pathname ?? '/dashboard'
    navigate(redirectPath, { replace: true })
  }

  const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault()
    setError(null)
    setInfo(null)

    if (mode === 'register' && verificationPending) {
      if (!pendingEmail || !pendingPassword) {
        setError('注册信息已失效，请重新填写后再验证')
        resetVerificationState()
        return
      }
      if (!verificationCode.trim()) {
        setError('请输入验证码')
        return
      }
      try {
        await verifyEmailMutation.mutateAsync({ email: pendingEmail, code: verificationCode.trim() })
        setInfo('验证成功，正在登录...')
        await finalizeLogin({ email: pendingEmail, password: pendingPassword })
        resetVerificationState()
      } catch (err) {
        const message = parseError(err)
        setError(message)
      }
      return
    }

    const formData = new FormData(event.currentTarget)
    const emailRaw = formData.get('email')
    const usernameRaw = formData.get('username')
    const passwordRaw = formData.get('password')

    const email = typeof emailRaw === 'string' ? emailRaw.trim() : ''
    const username = typeof usernameRaw === 'string' ? usernameRaw.trim() : ''
    const password = typeof passwordRaw === 'string' ? passwordRaw.trim() : ''

    if (!password) {
      setError('请输入密码')
      return
    }

    if (mode === 'login') {
      if (loginIdentifier === 'email' && !email) {
        setError('请输入邮箱')
        return
      }
      if (loginIdentifier === 'username' && !username) {
        setError('请输入用户名')
        return
      }
    } else if (!email || !username) {
      setError('注册需要填写邮箱和用户名')
      return
    }

    try {
      if (mode === 'register') {
        const registered = await registerMutation.mutateAsync({ email, username, password })
        setPendingEmail(registered.email)
        setPendingPassword(password)
        setPendingUsername(registered.username)
        setVerificationPending(true)
        setVerificationCode('')
        setInfo(`验证码已发送至 ${registered.email}，请在 10 分钟内输入邮件中的 6 位数字完成验证。`)
        return
      }

      const loginPayload =
        loginIdentifier === 'email'
          ? { email, password }
          : { username, password }

      await finalizeLogin(loginPayload)
    } catch (err) {
      const message = parseError(err)
      setError(message)
    }
  }

  const handleResendCode = async () => {
    if (!pendingEmail) {
      setError('请先提交注册信息以获取验证码')
      return
    }
    setError(null)
    try {
      await resendVerificationMutation.mutateAsync({ email: pendingEmail })
      setInfo(`验证码已重新发送至 ${pendingEmail}，请查收邮箱。`)
    } catch (err) {
      const message = parseError(err)
      setError(message)
    }
  }

  const handleUseAnotherEmail = () => {
    resetVerificationState()
    setInfo(null)
    setError(null)
    setMode('register')
    setLoginIdentifier('email')
  }

  const isSubmitting = loginMutation.isPending || registerMutation.isPending || verifyEmailMutation.isPending
  const isResending = resendVerificationMutation.isPending

  return (
    <div className="flex min-h-screen items-center justify-center bg-gradient-to-b from-slate-50 via-white to-blush-50 px-4 py-16">
      <div className="glass-panel relative w-full max-w-3xl overflow-hidden bg-white/90">
        <div className="grid gap-8 p-8 lg:grid-cols-[1.1fr_1fr] lg:p-12">
          <aside className="hidden flex-col justify-between rounded-3xl bg-gradient-to-br from-blush-400 via-blush-500 to-sky-500 p-8 text-white lg:flex">
            <div>
              <span className="rounded-full bg-white/20 px-3 py-1 text-xs font-semibold uppercase tracking-widest">
                Love Notes
              </span>
              <h2 className="mt-6 font-display text-3xl font-semibold leading-tight">
                邀你进入
                <br />
                专属恋爱空间
              </h2>
              <p className="mt-4 text-sm leading-relaxed text-white/80">
                使用邮箱验证码与用户名注册，支持双人共享，同步日记、纪念日、生理期记录。
              </p>
            </div>
            <div className="rounded-2xl bg-white/15 p-6 text-sm text-white/80">
              <p>✨ LangChain AI 助手会根据你们的情绪标签，生成关怀建议与惊喜灵感。</p>
            </div>
          </aside>
          <section className="flex flex-col">
            <div className="flex items-center justify-between">
              <h2 className="font-display text-2xl font-semibold text-slate-900">
                {mode === 'login' ? '欢迎回来' : verificationPending ? '完成邮箱验证' : '创建新账号'}
              </h2>
              <div className="flex gap-2 rounded-full border border-slate-200 p-1 text-xs">
                <button
                  type="button"
                  onClick={() => {
                    resetVerificationState()
                    setMode('login')
                    setError(null)
                    setInfo(null)
                  }}
                  className={`rounded-full px-3 py-1 font-medium ${mode === 'login' ? 'bg-slate-900 text-white' : 'text-slate-500'}`}
                  disabled={isSubmitting}
                >
                  登录
                </button>
                <button
                  type="button"
                  onClick={() => {
                    resetVerificationState()
                    setMode('register')
                    setLoginIdentifier('email')
                    setError(null)
                    setInfo(null)
                  }}
                  className={`rounded-full px-3 py-1 font-medium ${mode === 'register' ? 'bg-slate-900 text-white' : 'text-slate-500'}`}
                  disabled={isSubmitting}
                >
                  注册
                </button>
              </div>
            </div>
            <p className="mt-2 text-sm text-slate-500">
              登录即表示同意
              <Link to="/terms" className="text-blush-500">
                《服务条款》
              </Link>
              与
              <Link to="/privacy" className="text-blush-500">
                《隐私政策》
              </Link>
              。
            </p>
            <form className="mt-8 space-y-4" onSubmit={handleSubmit}>
              {mode === 'login' ? (
                <>
                  <div className="flex items-center gap-2 rounded-full border border-slate-200 p-1 text-xs">
                    <button
                      type="button"
                      onClick={() => setLoginIdentifier('email')}
                      className={`rounded-full px-3 py-1 font-medium ${loginIdentifier === 'email' ? 'bg-slate-900 text-white' : 'text-slate-500'}`}
                      disabled={isSubmitting}
                    >
                      邮箱登录
                    </button>
                    <button
                      type="button"
                      onClick={() => setLoginIdentifier('username')}
                      className={`rounded-full px-3 py-1 font-medium ${loginIdentifier === 'username' ? 'bg-slate-900 text-white' : 'text-slate-500'}`}
                      disabled={isSubmitting}
                    >
                      用户名登录
                    </button>
                  </div>
                  {loginIdentifier === 'email' ? (
                    <FormField
                      label="邮箱"
                      name="email"
                      type="email"
                      placeholder="lovely@note.app"
                      icon={<EnvelopeIcon className="h-5 w-5 text-slate-400" />}
                    />
                  ) : (
                    <FormField
                      label="用户名"
                      name="username"
                      placeholder="lovebird"
                      icon={<UserIcon className="h-5 w-5 text-slate-400" />}
                    />
                  )}
                  <FormField
                    label="密码"
                    name="password"
                    type="password"
                    placeholder="至少 8 位，包含字母与数字"
                    icon={<LockClosedIcon className="h-5 w-5 text-slate-400" />}
                  />
                  <div className="flex items-center justify-between text-sm text-slate-500">
                  <label className="flex items-center gap-2">
                    <input
                      type="checkbox"
                      checked={rememberMe}
                      onChange={(e) => setRememberMe(e.target.checked)}
                      className="h-4 w-4 rounded border-slate-300 text-blush-500 focus:ring-blush-500"
                    />
                    记住我
                  </label>
                    <Link to="/forgot-password" className="text-blush-500">
                      忘记密码？
                    </Link>
                  </div>
                </>
              ) : verificationPending ? (
                <>
                  <div className="rounded-2xl border border-dashed border-blush-200 bg-blush-50/60 px-4 py-3 text-sm text-slate-600">
                    <p>
                      {pendingUsername ?? '恋人'}，验证码已发送至&nbsp;
                      <span className="font-semibold text-slate-900">{pendingEmail}</span>。
                    </p>
                    <p className="mt-1 text-xs text-slate-500">如未收到，可尝试检查垃圾邮件，或 60 秒后重新发送。</p>
                  </div>
                  <label className="flex flex-col gap-2 text-sm font-medium text-slate-600">
                    验证码
                    <div className="relative">
                      <input
                        value={verificationCode}
                        onChange={(event) => setVerificationCode(event.target.value.replace(/\s+/g, ''))}
                        inputMode="numeric"
                        maxLength={6}
                        name="code"
                        placeholder="输入 6 位数字验证码"
                        className="h-11 w-full rounded-2xl border border-slate-200 bg-white px-4 text-center text-base tracking-[0.5em] text-slate-700 focus:border-blush-500 focus:outline-none focus:ring-2 focus:ring-blush-200"
                      />
                    </div>
                  </label>
                </>
              ) : (
                <>
                  <FormField
                    label="邮箱"
                    name="email"
                    type="email"
                    placeholder="lovely@note.app"
                    icon={<EnvelopeIcon className="h-5 w-5 text-slate-400" />}
                  />
                  <FormField
                    label="用户名"
                    name="username"
                    placeholder="lovebird"
                    icon={<UserIcon className="h-5 w-5 text-slate-400" />}
                  />
                  <FormField
                    label="密码"
                    name="password"
                    type="password"
                    placeholder="至少 8 位，包含字母与数字"
                    icon={<LockClosedIcon className="h-5 w-5 text-slate-400" />}
                  />
                  <p className="rounded-2xl bg-slate-50 px-4 py-3 text-sm text-slate-500">
                    提交注册后，我们会向你的邮箱发送 6 位验证码，完成验证即可自动登录。
                  </p>
                </>
              )}

              {error ? <p className="text-xs text-red-500">{error}</p> : null}
              {info ? <p className="text-xs text-emerald-500">{info}</p> : null}

              {mode === 'register' && verificationPending ? (
                <div className="flex flex-col gap-3">
                  <button
                    type="submit"
                    className="w-full rounded-full bg-gradient-to-r from-blush-500 to-sky-500 px-6 py-3 text-sm font-semibold text-white shadow-card transition hover:shadow-lg disabled:cursor-not-allowed disabled:opacity-60"
                    disabled={isSubmitting}
                  >
                    {isSubmitting ? '验证中...' : '验证并登录'}
                  </button>
                  <button
                    type="button"
                    onClick={handleResendCode}
                    className="rounded-full border border-slate-200 px-4 py-2 text-sm font-semibold text-slate-600 transition hover:border-blush-200 hover:text-blush-500 disabled:cursor-not-allowed disabled:opacity-60"
                    disabled={isResending || isSubmitting}
                  >
                    {isResending ? '发送验证码中...' : '重新发送验证码'}
                  </button>
                  <button
                    type="button"
                    onClick={handleUseAnotherEmail}
                    className="text-xs font-semibold text-slate-400 underline decoration-dotted underline-offset-4 disabled:cursor-not-allowed disabled:opacity-60"
                    disabled={isResending || isSubmitting}
                  >
                    使用其他邮箱注册
                  </button>
                </div>
              ) : (
                <button
                  type="submit"
                  className="mt-2 w-full rounded-full bg-gradient-to-r from-blush-500 to-sky-500 px-6 py-3 text-sm font-semibold text-white shadow-card transition hover:shadow-lg disabled:cursor-not-allowed disabled:opacity-60"
                  disabled={isSubmitting}
                >
                  {isSubmitting ? '处理中...' : mode === 'login' ? '登录' : '注册并发送验证码'}
                </button>
              )}
            </form>
            <p className="mt-6 text-center text-xs text-slate-400">
              支持邮箱登录与用户名登录，后台将通过 LangChain 风控链检测异常行为。
            </p>
          </section>
        </div>
      </div>
    </div>
  )
}

const FormField = ({ label, name, placeholder, type = 'text', icon }: FormFieldProps) => (
  <label className="flex flex-col gap-2 text-sm font-medium text-slate-600">
    {label}
    <div className="relative">
      {icon ? <span className="pointer-events-none absolute inset-y-0 left-3 flex items-center">{icon}</span> : null}
      <input
        name={name}
        type={type}
        placeholder={placeholder}
        className="h-11 w-full rounded-2xl border border-slate-200 bg-white px-4 pl-11 text-sm text-slate-700 shadow-inner focus:border-blush-500 focus:outline-none focus:ring-2 focus:ring-blush-200"
      />
    </div>
  </label>
)

export default AuthPage
